package com.lipiao.traveltreasure.controller.travelTreasure;

import com.lipiao.traveltreasure.bean.travelTreasureBean.ActivityBean;
import com.lipiao.traveltreasure.service.travelTreasure.ActivityService;
import com.lipiao.traveltreasure.util.UploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器-车行宝
 * 活动
 */
@Api(tags = "车行宝-活动信息接口")
@Controller
@RequestMapping(value = "/travelTreasureApi/activity")
public class ActivityController {

    private String TAG = "ActivityController";
    //注入业务对象
    @Resource
    private ActivityService activityService;
    //存储预返回页面的结果对象
    private Map<String, Object> result = new HashMap<>();
    //注入Bean对象

    //项目下存储头像的目录,需放在静态资源'static'目录下
    private final String uploadPath = "/static/upload/";

    /**
     * 1.获取所有活动信息/travelTreasureApi/activity/getActivityList
     *
     * @return 返回活动信息JSON
     */
    @ApiOperation(value = "获取用户信息", notes = "注意事项")
    @GetMapping("/getActivityList")
    @ResponseBody
    public Map<String, Object> getActivityList() {
        //防止返回信息重复
        result = new HashMap<>();
        try {
//            String[] words = new String[2000];
//            int m = 0;//读取文件至 words 字符串数组中
//            try {
//                BufferedReader br = new BufferedReader(
//                        new InputStreamReader(
//                                //new FileInputStream("src/Demo/words.txt")));
//                                new FileInputStream("D:\\javaeeprojects\\traveltreasure\\src\\main\\resources\\static\\oldtxt.txt")));
//                String line1;
//                while ((line1 = br.readLine()) != null) {
//                    //System.out.println(line1);//每行输出
//                    words[m] = line1;
//                    m++;
//                }//while
//                br.close();
//            } catch (Exception e) {
//                System.out.println("文件操作失败");
//                e.printStackTrace();
//            }
//            //字符串分割
//            for (int i = 0; i < words.length; i++) {
//                //分割 序列号+单词+英标 词性+中文释义
//                String[] result1 = words[i].split("]");
//                result1[0] += "]";
//                if (result1.length == 3) result1[1] = result1[1] + "]" + result1[2];
//                //转义符 \\ 分割result1[0]中的 序列号+单词  英标
//                String[] result2 = result1[0].split("\\[");
//                StringBuilder sb = new StringBuilder(result2[1]);//构造一个StringBuilder对象
//                sb.insert(0, "[");
//                result2[1] = sb.toString();
//                String[] result3 = result2[0].split(" ");
//                activityService.addword(new Word(result3[0], result3[1], result2[1], result1[1], 0));
//            }
            List<ActivityBean> list = activityService.findAll();
            //日志
            //LogUtil.getLogger().info(TAG + activityService.findAll().get(0).getStrActivityName());
            //System.out.println(activityService.findAll().get(0).getStrActivityName());
            //存储对象数据
            result.put("ActivityList", list);
            result.put("message", "getActivityListSuccess");
        } catch (Exception e) {
            result.put("ActivityList", "null");
            result.put("message", "getActivityListError");
            e.printStackTrace();
        } finally {
            return result;
        }

    }
//

    /**
     * 2.添加活动信息 /travelTreasureApi/activity/addActivity ActivityBean activityBean
     */
    @ApiOperation("添加活动信息")
    @PostMapping("/addActivity")
    @ResponseBody
    public Map<String, Object> addActivity(ActivityBean activityBean) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            //添加
            activityService.add(activityBean);
            //存储对象数据
            result.put("message", "addActivitySuccess");
        } catch (Exception e) {
            result.put("message", "addActivityError");
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 3.更新活动信息 根据id
     * /travelTreasureApi/activity/updateActivity ActivityBean activityBean
     */
    @ApiOperation("更新活动信息")
    @PostMapping("/updateActivity")
    @ResponseBody
    public Map<String, Object> updateActivity(ActivityBean activityBean) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            //首先判断该activityBean是否存在
            ActivityBean activityBean1 = activityService.findById(activityBean.getActivityId());
            if (activityBean1 != null) {
                //id不相等（不能修改id）
                if (activityBean.getActivityId() != activityBean1.getActivityId()) {
                    result.put("success", false);
                    result.put("msg", "该好友姓名已存在! 请检查后重试哟!");
                    return result;
                }
            }
            //添加操作
            if (activityService.modify(activityBean) > 0) {
                result.put("message", "updateActivitySuccess");
            } else {
                result.put("message", "服务器异常");
            }
            return result;
        } catch (Exception e) {
            result.put("message", "updateActivityError");
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 4.删除活动信息 根据id
     * /travelTreasureApi/activity/deleteActivity ActivityBean activityBean
     */
    @ApiOperation("根据id删除活动信息")
    @PostMapping("/deleteActivity")
    @ResponseBody
    public Map<String, Object> deleteActivity(long activityId) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            activityService.delete(activityId);
            result.put("message", "deleteActivitySuccess");

        } catch (Exception e) {
            result.put("message", "deleteActivityError");
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 5.上传头像
     *
     * @description: 上传头像-原理:将头像上传到项目发布目录中,通过读取数据库中的头像路径来显示头像
     * @param: activityPhoto
     * @param: request
     * @date: 2019-06-29 4:20 PM
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * /travelTreasureApi/activity/uploadPhoto
     */
    @ApiOperation("上传活动图片")
    @PostMapping("/uploadActivityPhoto")
    @ResponseBody
    public Map<String, Object> uploadPhoto(MultipartFile activityPhoto) throws FileNotFoundException, UnsupportedEncodingException {
        //指定存储头像目录的完整路径(项目发布路径): 若不使用绝对路径,则Spring boot会默认将上传的文件存储到临时目录中
        String dirPath = URLDecoder.decode(ResourceUtils.getURL("classpath:").getPath(), StandardCharsets.UTF_8.name()) + uploadPath;//加.name()
        //返回头像的上传结果
        return UploadFileUtil.getUploadResult(activityPhoto, dirPath, uploadPath);
    }

    /**
     * 6.获取指定商家活动信息/travelTreasureApi/activity/getMyActivityList
     *
     * @return 返回活动信息JSON
     * @param: sellerId 商家id
     */
    @ApiOperation(value = "获取指定商家的活动信息", notes = "注意事项")
    @GetMapping("/getMyActivityList")
    @ResponseBody
    public Map<String, Object> getMyActivityList(String sellerId) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            List<ActivityBean> list = activityService.findBySellerId(sellerId);
            //日志
//            LogUtil.getLogger().info(TAG + activityService.findAll().get(0).getStrActivityName());
            //存储对象数据
            result.put("ActivityList", list);
            result.put("message", "getMyActivityListSuccess");
        } catch (Exception e) {
            result.put("ActivityList", "null");
            result.put("message", "getMyActivityListError");
            e.printStackTrace();
        } finally {
            return result;
        }

    }


    /**
     * 4.删除指定商家活动信息 根据id
     * /travelTreasureApi/activity/deleteActivity ActivityBean activityBean
     *
     * @param: sellerId 商家id
     * @param: activityId 活动id
     */
    @ApiOperation("根据id删除活动信息")
    @PostMapping("/deleteMyActivity")
    @ResponseBody
    public Map<String, Object> deleteMyActivity(String sellerId, long activityId) {
        //防止返回信息重复
        result = new HashMap<>();
        try {
            activityService.delete(sellerId, activityId);
            result.put("message", "deleteMyActivitySuccess");

        } catch (Exception e) {
            result.put("message", "deleteMyActivityError");
            e.printStackTrace();
        } finally {
            return result;
        }
    }


}
